KindEditor.plugin('wcpimgs', function(K) {
	var wcp_imgs_editor;
	var wcpImgsKnowdialog;
	wcp_imgs_editor = this, name = 'wcpimgs';
	// 点击图标时执行
	wcp_imgs_editor.clickToolbar(name, function() {
		wcpImgsKnowdialog = K
		.dialog( {
			width : 300,
			title : '批量上传图片',
			body : '<div style="margin:10px;height:350px;text-align: center;overflow:auto;">'+
			       '<div class="wcpMultiUploadButtonBox">'+
			       ' <span class="btn btn-info fileinput-button"> '+
			       '  <span>上传图片</span><span id="html5uploadProsess"></span>'+
			       '  <input id="fileupload" type="file" name="imgFile" multiple>'+
			       ' </span>'+
			       ' <span class="btn btn-info insertEditor" style="height:30px;padding-top:6px;font-size:12px;"> '+ 
			       '  <span>插入编辑器</span>'+  
			       ' </span>'+
			       '<br/>1.点击"上传附件"按钮或将文件拖入此框上传。<br/>2.点击"插入编辑器"将附件插入编辑器。</div>'+ 
				   '<div class="panel-body" style="height:250px;overflow:auto;margin-top:12px;" id="wcpimgFileListId"><div id="fileQueue"></div></div>'+
				   '</div>',
			closeBtn : {
				name : '关闭',
				click : function(e) {
					wcpImgsKnowdialog.remove();
				}
			}
		});
		$('.wcpMultiUploadButtonBox .insertEditor').click(function(){
			$('.uploadedFileUnit').each(function(i,obj){
				//获得id
				var fileUrl=$(obj).children("input").val();
				//拼装img
				var tag='<img src="'+fileUrl+'" alt="" />';
				//插入img
				wcp_imgs_editor.insertHtml(tag);
			});
			wcpImgsKnowdialog.remove();
		});
		$('.wcpMultiUploadButtonBox #fileupload').fileupload({
			url : "upload/generalKindEditorImg.do",
			dataType : 'json',
			done : function(e, data) {
				var url=data.result.url;
				var error=data.result.error;
				var message=data.result.message;
				var id=data.result.id;
				var fileName=data.result.fileName;
				//alert("url:"+url);
				if(error!=0){
					wcpImgsKnowdialog.remove();
					alert(message);
					return;
				}
				addFileNodeByWcpImg('download/Pubicon.do?id='+id, decodeURIComponent(fileName), id,url);
			},
			progressall : function(e, data) {
				var progress = parseInt(data.loaded / data.total * 100, 10);
				$('#html5uploadProsess').text(progress + '%');
			}
		});
		$('body').bind('drop', function(ev) {
			ev.stopPropagation();
			ev.preventDefault();
		});
		initDropBox(); 
	});
	
	//初始化拖拽框
	function initDropBox(){
		var uploadDrop = $('.wcpMultiUploadButtonBox');
		uploadDrop = uploadDrop[0];
		uploadDrop.addEventListener('dragover', function(event) {
			$('.wcpMultiUploadButtonBox').addClass("active");
			event.preventDefault();
		});
		uploadDrop.addEventListener('dragenter', function(event) {
			event.preventDefault();
		});
		uploadDrop.addEventListener('dragleave', function(event) {
			$('.wcpMultiUploadButtonBox').removeClass("active");
			event.preventDefault();
		});
		uploadDrop.addEventListener('drop', function(event) {
			$('.wcpMultiUploadButtonBox').removeClass("active");
			event.preventDefault();
			var fileList = Array.from(event.dataTransfer.files);
			var uploadAble = updateFileValidate(fileList);
			$('#wcpimgFileListId').html('');
			if (uploadAble) {
				for (var i = 0; i < fileList.length; i++) {
					sendFileByXHR('upload/general.do', fileList[i]);
				}
			}
		});
	}
	//上传拖拽文件
	function sendFileByXHR(url, fielObj) {
		var xhr = new XMLHttpRequest();
		xhr.upload.onprogress = function(event) {
			var progress = parseInt(event.loaded / event.total * 100, 10);
			$('#html5uploadProsess').text(progress + '%');
		}
		xhr.onreadystatechange = function() {
			if (xhr.status === 200 && xhr.readyState === 4) {
				var jsonObject = JSON.parse(xhr.responseText, null);
				if(jsonObject.STATE==1){
					alert(jsonObject.MESSAGE);
				}else{
					var url=jsonObject.downurl;
					var viewurl=jsonObject.viewurl;
					addFileNodeByWcpImg('download/Pubicon.do?id=' + jsonObject.id
							, decodeURIComponent(jsonObject.fileName)
							, jsonObject.id
							,url,viewurl)
				}
			}
		}
		xhr.onabort = function(event) {
			//终止
			console.log('abort');
		}
		xhr.onerror = function(event) {
			console.log('error');
			alert('xhr.onerror-error');
		}
		var data = new FormData();
		data.append("file", fielObj);
		xhr.open('POST', url, true);
		xhr.send(data);
	}
	
	//插入图片到长传组件
	function addFileNodeByWcpImg(imgUrl, fileName, fileId,url) {
		var html = '<div class="col-md-12 file-block-box uploadedFileUnit" id="file_'+fileId+'">';
		html = html + '		<div class="stream-item" >';
		html = html + '				<div class="media">';
		html = html + '					<div class="pull-left">';
		html = html + '						<img  alt="'+fileName+'" src="'+imgUrl+'">';
		html = html + '					</div>';
		html = html + '					<div class="media-body" >';
		html = html + '							<i onclick="removeImgFile(\'' + fileId
				+ '\');" class="glyphicon glyphicon-remove pull-right" ></i>';
		html = html + '						<div class="file-title" >' + fileName + '</div>';
		html = html + '					</div>';
		html = html + '				</div>';
		html = html + '		</div>';
		html = html
				+ '<input type="hidden" name="fileUrl" value="'+url+'" /></div>';
		$('#wcpimgFileListId').append(html);
	}
	//检查上传文件，返回值为是否允许上传
	function updateFileValidate(files) {
		var maxFileNum=5;
		var maxSize=500000000;//500m
		var maxSizeTitle = (maxSize / 1024 / 1024).toFixed(2);
		if (files.length > maxFileNum) {
			alert("单次上传文件数量不能大于" + maxFileNum + "个!");
			return false;
		}
		var isOK = true;
		$(files).each(function(i, obj) {
			if (obj.size > maxSize) {
				alert("文件" + obj.name + "超大,请检查文件大小不能大于" + maxSizeTitle + "m");
				isOK = false;
			}
		});
		return isOK;
	}
	//kindeditor中粘贴图片直接上传到后台
	//edit 在 kindeditor的事件回调中可以通过 this.edit来获取pasteImgHandle(this.edit);
	
});
KindEditor.lang({
	wcpimgs : '批量上传图片'
});
function removeImgFile(fileId) {
	$("#file_" + fileId).remove();
}
function pasteImgHandle(editor,uploadUrl) {
	var doc = editor.edit.doc;
	var cmd = editor.edit.cmd;
	$(doc.body).bind('paste', function(ev) {
		var $this = $(this);
		var dataItem = ev.originalEvent.clipboardData.items[0];
		if (dataItem) {
			var file = dataItem.getAsFile();
			if (file) {
				var reader = new FileReader();
				reader.onload = function(evt) {
					var imageDataBase64 = evt.target.result;
					$.post(uploadUrl, {
						'base64' : imageDataBase64,
						'filename' : '粘贴图片.png'
					}, function(json) {
						if(json.STATE==0){
							//var html = '<img src="' + json.url + '" alt="'+json.fileName+'" />';
							//cmd.inserthtml(html);
							editor.exec('insertimage', json.url, "粘贴图片", undefined, undefined, undefined, undefined);  
						}else{
							cmd.inserthtml(json.message);
						}
					},'json');
				};
				var event = ev || window.event;//兼容IE
				//取消事件相关的默认行为
				if (event.preventDefault) //标准技术
				{
					event.preventDefault();
				}
				if (event.returnValue) //兼容IE9之前的IE
				{
					event.returnValue = false;
				}
				reader.readAsDataURL(file);
			}
		}
	});
}